// pages/audioRoom/audioRoom.js
import {audioRoomAPI} from '../../api/audioRoom/index'
import {$await} from '../../utils/util';
const CONFIG = require('../../config');
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
	imgsrc:'',
	ewm:true,
	img_url:'https://images.weserv.nl/?url=',
	avatar:CONFIG.imgUrlAvatar,
	isCreate:'',
	noType:'../../images/audioRoom/null.png',
	add:'../../images/audioRoom/add-room.png',
	gray:'../../images/audioRoom/gray-room.png',
	mine:'',
	master:0,
	roomList:[
		// {
		// 	title:'用打的方适教育孩子合适吗',
		// 	start:'2021-04-01 15:34:56',
		// 	num:'88',
		// 	name:'谢华',
		// 	btn:'管理房间',
		// 	master:1,
		// },
		
	],
	//房间number
    room_number:'',
    page:1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		console.log(options)
		console.log( decodeURIComponent(options.scene))
			// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
			const scene = decodeURIComponent(options.scene)
			if(options.scene){
				this.setData({
					room_number:scene
				})
			}else if(options.room_number){
				this.setData({
					room_number:options.room_number
				})
				
			}else{
			}
   
	
  },
  addRoom(){
	wx.navigateTo({
		url:'/pages/createRoom/createRoom'
	})  
  },
  toRoom(e){
		console.log(this.data.roomList)
	  let idx = e.target.dataset.index;
	  let roomList = this.data.roomList;
	  let roomNumber = roomList[idx].room_number;
	  if(roomList[idx].mine==0 && roomList[idx].status==0 && roomList[idx].reserve_state==0){		
		this.orderRoom(roomNumber,1)//马上预约
	  }else if(roomList[idx].mine==0 && roomList[idx].status==0 && roomList[idx].reserve_state==1){
		this.orderRoom(roomNumber,0)//取消预约
	  }else{
			if(roomList[idx].status==1){
				wx.navigateTo({
					url:'/pages/audioRoom/audioRoom?roomNumber='+roomNumber+'&from1=wxapp'
				})   
			}else{
				wx.navigateTo({
					url:"/pages/roomManage/roomManage?roomNumber="+roomNumber,
				})
			}

	  }
	  
	},
	
  subscribe(){	 
	 wx.navigateTo({
		url:'/pages/subscribe/subscribe'
	 })
  },
   // 获取房间列表
   async roomList(page,pageSize,room_number){
		 var that =this
		 console.log(room_number)
		 if(room_number){
			var data = {page,pageSize,room_number}
		 }else{
			var data = {page,pageSize}
		 }
	   let [err,res] = await $await(audioRoomAPI.roomList(data));
		 console.log(res)
		 if(room_number){
			if(res.list.length==0){
				wx.showToast({
					title: '房间未开始或已结束',
					icon: "none",
					duration: 1000
			})
			setTimeout(function () {
				that.roomList(1,10)
			 }, 1000)
			
			 }
		 }
		 if(this.data.page == 1){
				this.setData({
					roomList: res.list,
					isCreate:res.create,
				})	
		 }else{
			this.setData({
				roomList: this.data.roomList.concat(res.list),
				isCreate:res.create,
			})	
		 }
	  //  if(res.list.length>0){
	  //  	this.setData({
	  //  		roomList: res.list,
		// 	isCreate:res.create,
	  //  	})	
	  //  }else{
		//    let page = this.data.page-1
		//    if(page<1) page=1
		//    this.setData({
		// 	   roomList: res.list,
		// 	   page
		// 	 })
	  //  }
   },
   // 预约房间
   async orderRoom(room_number,reserve_type){
				let data = {room_number,reserve_type}
   	   let [err,res] = await $await(audioRoomAPI.orderRoom(data));
   	   if(res.status==1 && reserve_type==1){
			wx.showToast({
				 title: '预约成功',
				 icon: "none",
				 duration: 1000
			})
   	   }else if(res.status==1 && reserve_type==0){
		   wx.showToast({
		   	 title: '取消成功',
		   	 icon: "none",
		   	 duration: 1000
		   })
	   }
	   this.roomList(this.data.page,10,this.data.room_number)
	 },
	    //生成分享的二维码
	async getUnlimited(e){
				
				console.log(e)
   	   let data = {
					'scene':e.currentTarget.dataset.number,
					 'page': 'pages/salon/salon',
					 'width':'400',
					//  'auto_color': false,
					//  'line_color':[{"r":0,"g":0,"b":0}],
						// 'is_hyaline':true
				}
				
   	   let [err,res] = await $await(audioRoomAPI.getUnlimited(data));
   	   if(res){
					console.log(res)
					let url = 'data:image/png;base64,' + res.buffer
					this.setData({
						imgsrc:url,
						ewm:false
					})

   	   }else{
		   wx.showToast({
		   	 title: res.m,
		   	 icon: "none",
		   	 duration: 1000
		   })
	   } 
	 },
	 ewmHide(){
		this.setData({
			ewm:true
		})
	 },
	saveimg:function(){
		var _this=this
		this.setData({
			ewm:true
		})
    //获取文件管理器对象
    const fs = wx.getFileSystemManager()
    
    //文件保存路径
    const Imgpath = wx.env.USER_DATA_PATH + '/qrcodeImg' + '.png'
    //_this.data.imgsrc   base64图片文件
    let imageSrc = _this.data.imgsrc.replace(/^data:image\/\w+;base64,/, '')
    
    //写入本地文件
    fs.writeFile({
      filePath: Imgpath,
      data: imageSrc,
      encoding: 'base64',
      success (res) {
        console.log(res)
        
        //保存到手机相册
        wx.saveImageToPhotosAlbum({
          filePath: Imgpath,
          success(res) {
            console.log(res)
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            })
          },
          fail:function(err){
            console.log("失败了")
            console.log(err)
          }
        })
        
        
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
		if(this.data.room_number == ''){
			this.roomList(this.data.page,10)
		}else{
			this.roomList(this.data.page,10,this.data.room_number)
		}
		
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
	wx.showToast({
	      title: 'loading...',
	      icon: 'loading'
	})
	this.roomList(this.data.page,10,this.data.room_number)
	setTimeout(function(){
		wx.stopPullDownRefresh({
		  complete(res) {
		    wx.hideToast()
		    console.log(res, new Date())
		  }
		})
	},500)
  },
  stopPullDownRefresh() {
      wx.stopPullDownRefresh({
        complete(res) {
          wx.hideToast()
          console.log(res, new Date())
        }
      })
   },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
	this.setData({
		page:this.data.page += 1
	})
    this.roomList(this.data.page,10)
    console.log(this.data.page)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

	},

})